package com.mobis.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;

@Component
public class MangerFilter extends ZuulFilter {

    @Autowired
    public JwtUtils jwtUtils;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        
        System.out.println("来到了后台过滤器");
        RequestContext requestContext=RequestContext.getCurrentContext();

        HttpServletRequest request=requestContext.getRequest();
        String header=request.getHeader("Authorization");
        if (null!=header){
            String token=header.substring(7);
            if (null!=token&&!"".equals(token)){
                Claims claims=jwtUtils.parseJWT(header);
                if ("admin".equals(claims.get("roles"))){
                    //把信息头传先去并放行
                    requestContext.addZuulRequestHeader("Authorization",header);
                    return null;
                }
            }
        }

        requestContext.setSendZuulResponse(false);//终止运行
        requestContext.setResponseStatusCode(401);
        requestContext.getResponse().setContentType("text/html;charset=utf-8");
        requestContext.setResponseBody("权限不足");
        return null;
    }
}
